package com.example.courseapp.data

import android.content.Context
import android.content.SharedPreferences
import android.text.TextUtils
import android.util.Log
import com.example.courseapp.data.model.UserInfo

class DataPreferences {

    /**
     * 存储登陆数据
     */
    fun saveUserInfo(context: Context, username: kotlin.String?, password: kotlin.String?){
        // Context.MODE_PRIVATE表示SharePrefences的数据只有自己应用程序能访问。
        val sp: SharedPreferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE)
        val editor: SharedPreferences.Editor = sp.edit()
        // edit.putString("键名","值");
        editor.putString("USER_NAME", username)
        // 随机生成一个ID
        editor.putString("ID",username+ StrictMath.random())
        editor.putString("PASSWORD",password)
        editor.commit();
        editor.apply()
    }

    /**
     * 从存储的登陆数据中获取登录名
     */
    fun takeName(context: Context): kotlin.String? {
        val sharedPreferences: SharedPreferences = context.getSharedPreferences("usesrInfo", 0)
        //return sharedPreferences.getString("USER_NAME", null)
        return sharedPreferences.getString("USER_NAME",null)
    }

    /**
     *
     * 获取用户信息model
     * @param context
     * @param
     * @param
     */
    fun getUserInfo(context: Context): UserInfo?{
        val sp: SharedPreferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE)
        val userInfo: UserInfo = UserInfo()
        userInfo.userName= sp.getString("USER_NAME", "").toString()
        userInfo.userId= sp.getString("ID", "").toString()
        return userInfo
    }

    /**
     * userInfo中是否有数据
     */
    fun hasUserInfo(context: Context): kotlin.Boolean{
        val userInfo: UserInfo? = getUserInfo(context)
        if (userInfo != null){
            //有数据
            return (!TextUtils.isEmpty(userInfo.userName)) && (!TextUtils.isEmpty(userInfo.userId))
        }
        return false
    }

    /**
     * 清除登陆数据
     */
    fun clear(context: Context){
        val preferences: SharedPreferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE)
        val editor: SharedPreferences.Editor = preferences.edit()
        editor.clear()
        editor.commit()
        Log.d("data preference clear","clear Pref")
    }
}